<template>
  <div class="container">
    <!-- 统计卡片区域 -->
    <a-row :gutter="16">
      <a-col :span="6" v-for="(card, index) in statisticsCards" :key="index">
        <div class="data-card">
          <div class="card-content">
            <div class="card-title">{{ card.title }}</div>
            <div class="card-value" :style="{ color: card.color }">{{ card.value }}</div>
            <div class="card-desc">{{ card.desc }}</div>
          </div>
          <div class="card-icon" :style="{ backgroundColor: `${card.color}1a`, color: card.color }">
            <component :is="card.icon" :style="{ fontSize: '28px' }" />
          </div>
        </div>
      </a-col>
    </a-row>

    <!-- 入库申请流程 -->
    <a-card class="general-card">
      <template #title>入库流程状态</template>
      <template #extra>
        <a-button type="primary" @click="openCreateModal">
          <template #icon><icon-plus /></template>
          新建入库单
        </a-button>
      </template>
      <a-steps :current="1" style="margin: 20px 0">
        <a-step title="提交入库" description="填写入库单信息" />
        <a-step title="验收入库" description="仓库核对货物并收货" />
        <a-step title="完成上架" description="货物放入指定库位" />
      </a-steps>
      
      <a-divider />
      
      <a-row :gutter="[16, 16]">
        <a-col :span="12">
          <a-statistic 
            title="本月新增入库申请" 
            :value="inboundStore.inboundStatistics?.totalOrders || 0" 
            style="margin-bottom: 12px"
          >
            <template #suffix>
              <span style="font-size: 14px; color: #52c41a; margin-left: 8px;">
                <icon-arrow-rise style="vertical-align: middle;" /> 15.2%
              </span>
            </template>
          </a-statistic>
          <div ref="trendChartRef" style="height: 250px;"></div>
        </a-col>
        <a-col :span="12">
          <a-statistic 
            title="入库单货物总数" 
            :value="inboundStore.inboundStatistics?.totalQuantity || 0" 
            style="margin-bottom: 12px"
          >
            <template #suffix>
              <span>种</span>
              <span style="font-size: 14px; color: #52c41a; margin-left: 8px;">
                <icon-arrow-rise style="vertical-align: middle;" /> 8.5%
              </span>
            </template>
          </a-statistic>
          <div ref="statusChartRef" style="height: 250px;"></div>
        </a-col>
      </a-row>
    </a-card>

    <!-- 入库单列表 -->
    <a-card class="general-card">
      <template #title>入库单列表</template>
      <template #extra>
        <a-space>
          <a-select
            v-model="filterConditions.status"
            placeholder="入库单状态"
            allow-clear
            style="width: 120px"
          >
            <a-option value="">全部状态</a-option>
            <a-option value="1">待收货</a-option>
            <a-option value="2">待上架</a-option> 
            <a-option value="3">已完成</a-option>
            <a-option value="0">已取消</a-option>
          </a-select>
          <a-range-picker
            v-model="filterConditions.dateRange"
            style="width: 240px"
            allow-clear
          />
          <a-input-search
            v-model="filterConditions.searchKeyword"
            placeholder="搜索单号/供应商"
            style="width: 200px"
            allow-clear
            @search="handleFilterChange"
          />
          <a-button @click="refreshList">
            <template #icon><icon-refresh /></template>
            刷新
          </a-button>
        </a-space>
      </template>
      <a-table
        :data="filteredInboundList"
        :loading="loading"
        :pagination="pagination"
        :bordered="false"
        row-key="id"
        stripe
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #columns>
          <a-table-column title="入库单号" data-index="code" :width="140" />
          <a-table-column title="供应商" data-index="supplier.name" :width="160" />
          <a-table-column title="仓库" data-index="warehouse.name" :width="100" />
          <a-table-column title="货物种类数" :width="110" :sortable="{ sortDirections: ['ascend', 'descend'] }" >
             <template #cell="{ record }">
                {{ record.items ? record.items.length : 0 }}
             </template>
          </a-table-column>
          <a-table-column title="预计到货时间" data-index="expected_time" :width="180" :sortable="{ sortDirections: ['ascend', 'descend'] }" >
            <template #cell="{ record }">
              {{ record.expected_time ? formatTime(record.expected_time) : formatTime(record.created_at) }}
            </template>
          </a-table-column>
          <a-table-column title="申请时间" data-index="created_at" :width="180" :sortable="{ sortDirections: ['ascend', 'descend'] }" >
            <template #cell="{ record }">
              {{ formatTime(record.created_at) }}
            </template>
          </a-table-column>
          <a-table-column title="状态" data-index="status" :width="100">
            <template #cell="{ record }">
              <a-tag :color="getInboundStatusColor(record.status)">{{ getInboundStatusText(record.status) }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="操作" fixed="right" :width="200">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="viewDetail(record.id)">
                  <template #icon><icon-eye /></template>
                  查看
                </a-button>
                <a-button type="text" status="success" size="small" v-if="record.status == 1" @click="startReceiving(record.id)">
                  <template #icon><icon-check-circle /></template>
                  去收货
                </a-button>
                <a-button type="text" status="warning" size="small" v-if="record.status == 2" @click="startPutaway(record.id)">
                  <template #icon><icon-storage /></template>
                  去上架
                </a-button>
                <a-button 
                  type="text" 
                  status="danger" 
                  size="small" 
                  v-if="record.status == 1" 
                  @click="confirmCancel(record.id)"  
                >
                  <template #icon><icon-close-circle /></template>
                  取消
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 入库单详情模态框 -->
    <a-modal
      v-model:visible="detailVisible"
      title="入库单详情"
      :width="1100"
      :footer="false"
      :unmount-on-close="true"
    >
      <a-spin :loading="detailLoading">
        <a-descriptions title="基本信息" :data="detailInfo" :column="3" bordered size="small" :label-style="{ width: '110px' }"/>
        
        <div style="margin-top: 16px;">
          <a-typography-title :heading="6">入库货物信息</a-typography-title>
          <a-table 
            :data="detailItems" 
            :pagination="false" 
            :bordered="{cell:true}" 
            size="small" 
            :scroll="{ y: '240px' }" 
            row-key="id"
            stripe
          >
            <template #columns>
               <a-table-column title="序号" :width="50" align="center">
                 <template #cell="{ rowIndex }">{{ rowIndex + 1 }}</template>
               </a-table-column>
               <a-table-column title="货物编码" data-index="cargo.code" :width="125" align="center" ellipsis tooltip>
                 <template #cell="{ record }">{{ record.cargo?.code || '-' }}</template>
               </a-table-column>
               <a-table-column title="货物名称" data-index="cargo.name" align="center" ellipsis tooltip>
                 <template #cell="{ record }">{{ record.cargo?.name || '-' }}</template>
               </a-table-column>
               <a-table-column title="规格" data-index="cargo.spec" :width="110" align="center" ellipsis tooltip>
                  <template #cell="{ record }">{{ record.cargo?.spec || record.cargo?.specification || '-' }}</template>
               </a-table-column>
               <a-table-column title="单位" data-index="cargo.unit" :width="55" align="center">
                  <template #cell="{ record }">{{ record.cargo?.unit || '-' }}</template>
               </a-table-column>
               <a-table-column title="预期数量" data-index="quantity" :width="85" align="center"/>
               <a-table-column title="实收数量" data-index="received_quantity" :width="85" align="center">
                  <template #cell="{ record }">{{ record.received_quantity ?? '-' }}</template>
               </a-table-column>
               <a-table-column title="上架数量" data-index="putaway_quantity" :width="85" align="center">
                  <template #cell="{ record }">{{ record.putaway_quantity ?? '-' }}</template>
               </a-table-column>
                <a-table-column title="状态" :width="85" align="center">
                  <template #cell="{ record }">
                    <a-tag v-if="record.putaway_quantity >= record.quantity" color="green">已上架</a-tag>
                    <a-tag v-else-if="record.received_quantity >= record.quantity" color="blue">已收货</a-tag>
                    <a-tag v-else-if="record.received_quantity > 0" color="orange">部分收货</a-tag>
                    <a-tag v-else color="gray">待收货</a-tag>
                  </template>
                </a-table-column>
               <a-table-column title="备注" data-index="note" align="center" ellipsis tooltip>
                  <template #cell="{ record }">{{ record.note || '-' }}</template>
               </a-table-column>
            </template>
          </a-table>
        </div>
        
        <div style="margin-top: 24px; display: flex; justify-content: center; gap: 16px;">
          <a-button @click="closeDetail">关闭</a-button>
          <a-button v-if="currentDetail && currentDetail.status == 1" type="primary" status="success" @click="startReceiving(currentDetail.id)">去收货</a-button>
          <a-button v-if="currentDetail && currentDetail.status == 2" type="primary" status="warning" @click="startPutaway(currentDetail.id)">去上架</a-button>
          <a-button 
            v-if="currentDetail && currentDetail.status == 1" 
            type="primary" 
            status="danger" 
            @click="confirmCancel(currentDetail.id)"
          >
            取消入库
          </a-button> 
        </div>
      </a-spin>
    </a-modal>

    <!-- 新建入库单模态框 -->
    <a-modal
      v-model:visible="createModalVisible"
      title="新建入库单"
      :width="1000"
      @ok="handleCreateSubmit"
      @cancel="handleCreateCancel"
      :unmount-on-close="true"
      :mask-closable="false"
      :ok-loading="createLoading"
    >
      <a-form ref="createFormRef" :model="createForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="supplierId" label="供应商" :rules="[{ required: true, message: '请选择供应商'}]">
              <a-select 
                v-model="createForm.supplierId" 
                placeholder="请选择供应商" 
                allow-search
                :loading="loadingSuppliers" 
              >
                <a-option v-if="supplierList.length === 0" value="no-data" disabled>数据加载中或暂无供应商数据</a-option>
                <a-option v-for="supplier in supplierList" :key="supplier.id" :value="supplier.id">
                  {{ supplier.name || `${supplier.code}(无名称)` }}
                </a-option>
              </a-select>
              <div v-if="loadingSuppliers && !supplierList.length" class="text-gray-500 text-xs mt-1">
                正在加载供应商数据...
              </div>
              <div v-else-if="!loadingSuppliers && !supplierList.length" class="text-red-500 text-xs mt-1">
                未找到供应商数据，请检查网络或联系管理员添加供应商
              </div>
            </a-form-item>
          </a-col>
          <a-col :span="12">
             <a-form-item field="warehouseId" label="仓库" :rules="[{ required: true, message: '请选择仓库'}]">
               <a-select 
                 v-model="createForm.warehouseId" 
                 placeholder="请选择仓库"
                 :loading="loadingWarehouses"
               >
                 <a-option v-for="warehouse in warehouseList" :key="warehouse.id" :value="warehouse.id">{{ warehouse.name }}</a-option>
               </a-select>
             </a-form-item>
          </a-col>
         </a-row>
         <a-row :gutter="16">
            <a-col :span="12">
                <a-form-item 
                  field="expectedTime" 
                  label="预计到货时间"
                  :rules="[{ required: true, message: '请选择预计到货时间' }]"
                >
                    <a-date-picker v-model="createForm.expectedTime" style="width: 100%;" />
                </a-form-item>
            </a-col>
         </a-row>
        <a-form-item field="remark" label="备注">
            <a-textarea v-model="createForm.remark" placeholder="请输入备注信息" :auto-size="{minRows:2,maxRows:4}"/>
        </a-form-item>

        <!-- 货物信息区域 -->
        <a-divider>货物信息</a-divider>
        <a-row :gutter="16" align="end" style="margin-bottom: 16px;">
          <a-col :span="18">
            <a-form-item label="选择货物添加到列表" hide-label>
              <a-select
                v-model="selectedProductId"
                placeholder="搜索或选择货物"
                allow-search
                show-extra-options
                :options="productOptions" 
                :filter-option="(inputValue, option) => option.label.toLowerCase().includes(inputValue.toLowerCase())"
                @change="addProduct"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <!-- Optional: Button to add selected product if needed -->
          <!-- <a-col :span="6">
            <a-button type="primary" @click="addProduct" :disabled="!selectedProductId">添加货物</a-button>
          </a-col> -->
        </a-row>

        <!-- 货物明细表格 -->
        <a-table 
          :data="createForm.items"
          :pagination="false" 
          row-key="productId" 
          :bordered="{cell:true}"
        >
          <template #columns>
            <a-table-column title="货物名称" data-index="productName" />
            <a-table-column title="货物编码" data-index="productCode" />
            <a-table-column title="规格" data-index="specification" />
            <a-table-column title="单位" data-index="unit" />
            <a-table-column title="采购单价" :width="150">
              <template #cell="{ record }">
                <a-input-number 
                  v-model="record.unitPrice" 
                  placeholder="输入单价"
                  :min="0.01" 
                  :precision="2" 
                  style="width: 120px;"
                />
              </template>
            </a-table-column>
            <a-table-column title="预期数量" :width="150">
              <template #cell="{ record }">
                <a-input-number 
                  v-model="record.quantity"
                  placeholder="输入数量"
                  :min="1" 
                  :precision="0"
                  mode="button"
                  style="width: 120px;"
                />
              </template>
            </a-table-column>
             <a-table-column title="操作" :width="80">
               <template #cell="{ record, rowIndex }">
                 <a-button type="text" status="danger" size="small" @click="removeProduct(rowIndex)">
                   <template #icon><icon-delete /></template>
                 </a-button>
               </template>
             </a-table-column>
          </template>
        </a-table>
       </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, h, watch, nextTick, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { 
  IconPlus,
  IconRefresh,
  IconEye,
  IconCheck,
  IconCalendar,
  IconCheckCircle,
  IconCloseCircle,
  IconFile,
  IconStorage,
  IconClockCircle,
  IconExclamationCircle,
  IconArrowRise,
  IconArrowFall,
  IconDelete
} from '@arco-design/web-vue/es/icon';
import { Message, Modal } from '@arco-design/web-vue';
import { markRaw } from 'vue';
import { useWarehouseStore } from '@/stores/warehouse';
import { useSupplierStore } from '@/stores/supplier';
import { useCargoStore } from '@/stores/cargo';
import { useInboundStore } from '@/stores/inbound';
import dayjs from 'dayjs';
import { formatTime } from '@/utils/datetime';
import * as echarts from 'echarts';
import { debounce } from '@/utils/debounce';

const router = useRouter();
const warehouseStore = useWarehouseStore();
const supplierStore = useSupplierStore();
const cargoStore = useCargoStore();
const inboundStore = useInboundStore();

// 从 Store 获取状态映射函数
const { getInboundStatusColor, getInboundStatusText } = inboundStore;

// 统计卡片数据
const statisticsCards = ref([
  {
    title: '待收货',
    value: computed(() => inboundStore.inboundStatistics?.pendingReceipt || 0),
    desc: '等待仓库收货',
    icon: markRaw(IconStorage),
    color: '#FF7D00'
  },
  {
    title: '待上架',
    value: computed(() => inboundStore.inboundStatistics?.pendingPutaway || 0),
    desc: '等待放入库位',
    icon: markRaw(IconCheckCircle),
    color: '#165DFF'
  },
  {
    title: '今日已完成',
    value: computed(() => inboundStore.inboundStatistics?.completedToday || 0),
    desc: '今日完成入库',
    icon: markRaw(IconClockCircle),
    color: '#00B42A'
  },
  {
    title: '已取消单据',
    value: computed(() => inboundStore.inboundStatistics?.exceptionOrders || 0),
    desc: '已取消的订单',
    icon: markRaw(IconExclamationCircle),
    color: '#F53F3F'
  }
]);

// 筛选和搜索条件
const filterConditions = ref({
  status: '',
  dateRange: [],
  searchKeyword: ''
});
const loading = computed(() => inboundStore.loading);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100]
});

// 从store获取入库单列表
const inboundList = computed(() => inboundStore.inboundList);

// 根据筛选条件过滤入库单列表
const filteredInboundList = computed(() => {
  let result = [...inboundList.value];
  
  if (filterConditions.value.status) {
    result = result.filter(item => item.status === filterConditions.value.status);
  }
  
  if (filterConditions.value.dateRange && filterConditions.value.dateRange.length === 2) {
    const startDate = dayjs(filterConditions.value.dateRange[0]).startOf('day');
    const endDate = dayjs(filterConditions.value.dateRange[1]).endOf('day');
    result = result.filter(item => {
      const itemDate = dayjs(item.created_at);
      return itemDate.isAfter(startDate) && itemDate.isBefore(endDate);
    });
  }
  
  if (filterConditions.value.searchKeyword) {
    const keyword = filterConditions.value.searchKeyword.toLowerCase();
    result = result.filter(item => 
      item.code.toLowerCase().includes(keyword) || 
      item.supplier.name.toLowerCase().includes(keyword)
    );
  }
  
  return result;
});

// 处理页面变化
const handlePageChange = async (current) => {
  pagination.value.current = current;
  await fetchInboundList();
};

// 处理每页数量变化
const handlePageSizeChange = async (pageSize) => {
  pagination.value.pageSize = pageSize;
  await fetchInboundList();
};

// 获取入库单列表
const fetchInboundList = async () => {
  try {
    const params = {
      current: pagination.value.current,
      pageSize: pagination.value.pageSize,
      status: filterConditions.value.status || undefined,
      keyword: filterConditions.value.searchKeyword || undefined,
      startTime: filterConditions.value.dateRange && filterConditions.value.dateRange[0] ? dayjs(filterConditions.value.dateRange[0]).format('YYYY-MM-DD HH:mm:ss') : undefined,
      endTime: filterConditions.value.dateRange && filterConditions.value.dateRange[1] ? dayjs(filterConditions.value.dateRange[1]).format('YYYY-MM-DD HH:mm:ss') : undefined
    };
    
    const result = await inboundStore.getInboundList(params);
    if (result) {
      pagination.value.total = result.total;
      // 初始化图表
      initCharts();
    }
  } catch (error) {
    console.error('获取入库单列表失败:', error);
  } finally {
    // loading state is handled by store
  }
};

// 刷新列表
async function refreshList() {
  try {
    await fetchInboundList();
    return true;
  } catch (error) {
    console.error('刷新列表失败:', error);
    return false;
  }
}

// 详情模态框相关
const detailVisible = ref(false);
const detailLoading = ref(false);
const currentDetail = ref(null);
const detailInfo = ref([]);
const detailItems = ref([]);

// 查看详情
async function viewDetail(id) {
  detailLoading.value = true;
  currentDetail.value = null;
  detailInfo.value = [];
  detailItems.value = [];

  try {
    const result = await inboundStore.getInboundDetail(id);
    if (result) {
      currentDetail.value = result;
      
      // Basic info processing - Use helper and correct field names
      const displayValue = (value) => value ? value : '-';
      const displayTime = (time) => time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-';
      const typeMap = { 1: '采购入库', 2: '退货入库', 3: '其他入库' }; // Assuming inbound types

      detailInfo.value = [
        { label: '入库单号', value: displayValue(result.code) },
        { label: '状态', value: getInboundStatusText(result.status) }, // Use store's helper
        { label: '入库类型', value: typeMap[result.type] || `未知 (${result.type})` }, // Assuming type field
        { label: '供应商', value: displayValue(result.supplier?.name) },
        { label: '仓库', value: displayValue(result.warehouse?.name) },
        { label: '申请人', value: displayValue(result.user?.nickname || result.user?.username) }, // Assuming user field
        { label: '申请时间', value: displayTime(result.created_at) },
        { label: '预计到货时间', value: displayTime(result.expected_time) }, // Use expected_time
        { label: '备注', value: displayValue(result.note), span: 3 } // Use note
      ];
      
      // Cargo info processing - Ensure cargo is preloaded or handle potential null
      detailItems.value = (result.items || []).map(item => ({
        ...item,
        // Ensure nested cargo object is accessed safely
        cargo: item.cargo || {} 
      }));
      
      detailVisible.value = true;
    } else {
      Message.error('获取入库单详情失败：无效数据');
    }
  } catch (error) {
    console.error('获取入库单详情失败:', error);
    Message.error('获取入库单详情失败');
  } finally {
    detailLoading.value = false;
  }
}

// 关闭详情
function closeDetail() {
  detailVisible.value = false;
}

// 使用 Modal.confirm 替代 Popconfirm
const confirmCancel = (id) => {
  Modal.confirm({
    title: '确认取消',
    content: '确定要取消该入库单吗？此操作不可恢复。',
    titleAlign: 'start',
    okText: '确定取消',
    cancelText: '再想想',
    draggable: true,
    okButtonProps: { status: 'danger' },
    onOk: async () => {
      try {
        const result = await inboundStore.cancelInbound(id);
        if (result && result.success) {
          Message.success('入库单已取消');
          // 刷新列表
          refreshList(); // 使用正确的函数名
          // 如果详情模态框打开了且显示的是当前取消的入库单，则关闭它
          if (detailVisible.value && currentDetail.value && currentDetail.value.id === id) {
            detailVisible.value = false;
          }
        } else {
          Message.error(result?.message || '取消失败');
        }
      } catch (error) {
        console.error('取消入库单失败:', error);
        Message.error('取消操作异常');
      }
    }
  });
};

// 新建入库单模态框相关
const createModalVisible = ref(false);
const createFormRef = ref(null);
const createForm = ref({
  supplierId: null,
  warehouseId: null,
  expectedTime: null,
  remark: '',
  items: []
});
const createLoading = ref(false);

// 从仓库 Store 获取仓库列表和加载状态
const warehouseList = computed(() => warehouseStore.warehouseList || []);
const loadingWarehouses = computed(() => warehouseStore.warehouseLoading);

// 从 supplierStore 获取供应商列表
const supplierList = computed(() => supplierStore.suppliers || []);
const loadingSuppliers = computed(() => supplierStore.loading);

// 从 cargoStore 获取货物列表
const productList = computed(() => cargoStore.cargoList || []);
const loadingProducts = computed(() => cargoStore.loading);

// 将货物列表转换为 Select 组件的 options 格式
const productOptions = computed(() => 
  productList.value.map(p => ({ 
      value: p.id, 
      label: `${p.name} ${p.spec ? `(${p.spec})` : (p.specification ? `(${p.specification})` : '')}`  // 检查两种可能的规格字段名
    }))
);

// 获取下拉列表数据
async function fetchSelectData() {
    try {
        console.log('开始获取基础数据：供应商、仓库、货物');
        
        // 优先获取供应商数据
        await supplierStore.getAllSuppliers();
        
        console.log('供应商数据加载完成，当前数量:', supplierList.value.length);
        
        // 如果供应商数据为空，尝试再次加载
        if (supplierList.value.length === 0) {
            console.warn('供应商列表为空，尝试重新加载...');
            await supplierStore.getAllSuppliers();
            console.log('重试后供应商数量:', supplierList.value.length);
        }
        
        // 并行加载其他数据
        await Promise.all([
            warehouseStore.fetchWarehouses(),
            cargoStore.getCargoList()
        ]);
        
        return true;
    } catch (error) {
        console.error("获取基础数据失败:", error);
        Message.error("获取基础数据失败，请稍后重试");
        return false;
    }
}

// 打开新建模态框
async function openCreateModal() {
  createForm.value = {
    supplierId: null,
    warehouseId: null,
    expectedTime: dayjs().add(1, 'day'), // 默认设置为明天
    remark: '',
    items: []
  };
  selectedProductId.value = null;
  createFormRef.value?.clearValidate();
  
  // 在打开模态框前确保数据已加载完成
  if (!supplierList.value.length || !warehouseList.value.length || !productList.value.length) {
    Message.loading('正在加载基础数据...', 2000);
    await fetchSelectData();
  }
  
  createModalVisible.value = true;
}

// 添加货物到列表
const selectedProductId = ref(null);

function addProduct() {
  if (!selectedProductId.value) return;

  const existingItem = createForm.value.items.find(item => item.productId === selectedProductId.value);
  if (existingItem) {
    Message.warning('该货物已在列表中');
    setTimeout(() => selectedProductId.value = null, 0);
    return;
  }

  const product = productList.value.find(p => p.id === selectedProductId.value);
  if (product) {
    createForm.value.items.push({
      productId: product.id,
      productCode: product.code,
      productName: product.name,
      specification: product.spec || product.specification || '',
      unit: product.unit || '',
      quantity: 1,
      unitPrice: product.price || 0,
      remark: ''
    });
  } else {
    Message.error('未找到所选货物信息');
  }
  setTimeout(() => selectedProductId.value = null, 0);
}

function removeProduct(index) {
  createForm.value.items.splice(index, 1);
}

// 处理新建提交
async function handleCreateSubmit() {
  createLoading.value = true;
  try {
    const errors = await createFormRef.value?.validate();
    if (errors) {
      console.log("Form validation errors:", errors);
      return; 
    }
    
    if (!createForm.value.items || createForm.value.items.length === 0) {
        Message.error('请至少添加入库货物');
        return;
    }
    
    // 检查所有货物数量是否有效，合并为一次提示
    const invalidItems = createForm.value.items.filter(item => !item.quantity || item.quantity <= 0);
    if (invalidItems.length > 0) {
        Message.error(`有 ${invalidItems.length} 个货物数量无效，请检查`);
        return;
    }

    // 确保预计到货时间字段有值
    if (!createForm.value.expectedTime) {
      Message.error('请选择预计到货时间');
      return;
    }

    // 格式化预计到货时间，确保总是生成正确的ISO格式时间字符串
    const expectedTimeISO = dayjs(createForm.value.expectedTime).format('YYYY-MM-DDTHH:mm:ss.SSSZ');
    console.log('预计到货时间:', expectedTimeISO);

    const submitData = {
        warehouse_id: createForm.value.warehouseId, 
        notes: createForm.value.remark, 
        type: 1,
        supplier_id: createForm.value.supplierId, 
        expected_time: expectedTimeISO,
        items: createForm.value.items.map(item => ({
            cargo_id: item.productId,
            quantity: item.quantity,
            unit_price: item.unitPrice || 0,
        }))
    };

    console.log('提交新建入库单数据:', submitData);
    const result = await inboundStore.createInbound(submitData);
    console.log('新建入库单结果:', result);

    // 修复判断逻辑：检查result是否存在且success不为false
    if (result && result.success !== false) {
      Message.success('新建入库单成功');
      createModalVisible.value = false; 
      refreshList(); 
    } else {
      // 如果失败，显示错误消息
      Message.error(result?.message || '新建入库单失败');
    }

  } catch (error) {
      console.error("Error submitting create form:", error);
      Message.error('提交失败，请稍后重试');
  } finally {
      createLoading.value = false;
  }
}

// 处理新建取消
function handleCreateCancel() {
  createModalVisible.value = false;
}

// 开始收货
const startReceiving = (id) => {
  router.push({ name: 'ReceivingOperation', params: { id } });
};

// 开始上架
const startPutaway = (id) => {
  router.push({ name: 'PutawayOperation', params: { id } });
};

// 监听筛选条件变化，重新加载数据
const handleFilterChange = () => {
  pagination.value.current = 1;
  fetchInboundList();
};

// 监听筛选条件
const setupFilterWatchers = () => {
  // 监听状态变化
  watch(() => filterConditions.value.status, () => {
    console.log('状态筛选变更为:', filterConditions.value.status);
    handleFilterChange();
  });

  // 监听日期范围变化
  watch(() => filterConditions.value.dateRange, () => {
    console.log('日期范围变更为:', filterConditions.value.dateRange);
    handleFilterChange();
  });

  // 监听关键词变化 - 使用防抖
  watch(() => filterConditions.value.searchKeyword, debounce(() => {
    console.log('关键词变更为:', filterConditions.value.searchKeyword);
    handleFilterChange();
  }, 500));
};

// 图表相关
const trendChartRef = ref(null);
const statusChartRef = ref(null);
let trendChart = null;
let statusChart = null;

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    if (trendChartRef.value && !trendChart) {
      trendChart = echarts.init(trendChartRef.value);
    }
    if (statusChartRef.value && !statusChart) {
      statusChart = echarts.init(statusChartRef.value);
    }
    updateCharts();
  });
};

// 更新图表数据
const updateCharts = () => {
  if (trendChart) {
    const trendData = inboundStore.inboundStatistics?.monthlyTrend || [];
    const months = trendData.map(item => item.month);
    const counts = trendData.map(item => item.count);
    
    trendChart.setOption({
      title: {
        text: '入库单月度趋势',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: months
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '入库单数',
          type: 'bar',
          barWidth: '60%',
          data: counts,
          itemStyle: {
            color: '#8A6FF8'
          }
        }
      ]
    });
  }
  
  if (statusChart) {
    const statusData = inboundStore.inboundStatistics?.statusDistribution || [];
    
    statusChart.setOption({
      title: {
        text: '入库单状态分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: statusData.map(item => item.status)
      },
      series: [
        {
          name: '订单状态',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: statusData.map(item => ({
            name: item.status,
            value: item.value
          }))
        }
      ]
    });
  }
};

// 处理窗口大小变化，重新调整图表大小
const handleResize = () => {
  if (trendChart) {
    trendChart.resize();
  }
  if (statusChart) {
    statusChart.resize();
  }
};

// 页面挂载初始化
onMounted(async () => {
  console.log('入库单列表组件已挂载');
  // 设置筛选条件监听
  setupFilterWatchers();
  
  try {
    // 先加载基础数据
    await fetchSelectData();
    // 再加载入库单列表数据
    await refreshList();
  } catch (error) {
    console.error('初始化数据加载失败:', error);
  }
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize);
});

// 在组件卸载时移除事件监听和销毁图表实例
// 页面卸载清理资源
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (trendChart) {
    trendChart.dispose();
    trendChart = null;
  }
  if (statusChart) {
    statusChart.dispose();
    statusChart = null;
  }
});
</script>

<style lang="less" scoped>

.container {
  padding: 20px;
}


.data-card {
  height: 120px;
  padding: 20px;
  display: flex;
  background-color: var(--color-bg-2);
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  margin-bottom: 16px;

  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  .card-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .card-title {
    font-size: 14px;
    color: var(--color-text-2);
    margin-bottom: 8px;
  }

  .card-value {
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 8px;
  }

  .card-desc {
    font-size: 12px;
    color: var(--color-text-3);
  }

  .card-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 36px;
    opacity: 0.8;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    margin-left: 12px;
  }
}

.general-card {
  margin-bottom: 16px;
  
  :deep(.arco-card-header) {
    height: 52px;
    padding: 16px 20px;
    border-bottom: 1px solid var(--color-border);
  }
}
</style>